/**
 * jims
 */
package com.jims.master.modules.csm.service;

import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.PrintPdfUtils;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.csm.dao.ExpExportDetailDao;
import com.jims.master.modules.csm.dao.ExpExportMasterDao;
import com.jims.master.modules.csm.dao.ExpProvideApplicationDao;
import com.jims.master.modules.csm.dao.ExpStockDao;
import com.jims.master.modules.csm.entity.*;
import com.jims.master.modules.sys.dao.CompanyDao;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.utils.DictUtils;
import com.jims.master.modules.sys.utils.UserUtils;
import com.jims.master.modules.utils.ExpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消耗品发放生申请Service
 * @author zhuq
 * @version 2017-03-18
 */
@Service
@Transactional(readOnly = true)
public class ExpProvideApplicationService extends CrudService<ExpProvideApplicationDao, ExpProvideApplication> {
    @Autowired
    private ExpExportService expExportService;
    @Autowired
    private ExpStockDao expStockDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private ExpExportDetailDao expExportDetailDao;
    @Autowired
    private ExpExportMasterDao expExportMasterDao;

	public ExpProvideApplication get(String id) {
		return super.get(id);
	}

	public List<ExpProvideApplication> findList(ExpProvideApplication expProvideApplication) {
		return super.findList(expProvideApplication);
	}

	public Page<ExpProvideApplication> findPage(Page<ExpProvideApplication> page, ExpProvideApplication expProvideApplication) {
		return super.findPage(page, expProvideApplication);
	}

    /**
     * 查阅本库房所提申请
     * @param expProvideApplication
     * @param outFlag 发放标志
     * @return
     * @author fengyg
     * @date 2017-06-16
     */
    public Page<ExpProvideApplication> searchProvideApplication(ExpProvideApplication expProvideApplication,String outFlag){
        Page<ExpProvideApplication> page = new Page<ExpProvideApplication>();
        expProvideApplication.updateOrgId();
        if(null == expProvideApplication.getStorageIn()){
            expProvideApplication.setStorageIn(UserUtils.getUser().getOrgDept().getId());
        }
        if(StringUtils.isNotBlank(outFlag)){
            expProvideApplication.setOutFlag(outFlag);
        }
        List<ExpProvideApplication> list = dao.searchProvideApplication(expProvideApplication);
        if(null != list && list.size() > 0){
            for (ExpProvideApplication provideApplication : list) {
                provideApplication.setQuantity(provideApplication.getQuantity() / provideApplication.getPackageNum());
                if(null != provideApplication.getAuditQuantity()){
                    provideApplication.setAuditQuantity(provideApplication.getAuditQuantity() / provideApplication.getPackageNum());
                }
                if(null != provideApplication.getQuantityOut()){
                    provideApplication.setQuantityOut(provideApplication.getQuantityOut() / provideApplication.getPackageNum());
                }
            }
        }
        expProvideApplication.setPage(page);
        page.setList(list);
        return page;
    }

    /**
     * 科室申请审核保存
     * @param expProvideApplication
     * @return
     * @author fengyg
     * @date 2017-06-19
     */
    @Transactional(readOnly = false)
    public int saveAuditProvide(ExpProvideApplication expProvideApplication){
        int num = 0;
        if(null != expProvideApplication && expProvideApplication.getExpProvideApplicationList().size() > 0){
            List<ExpProvideApplication> list = expProvideApplication.getExpProvideApplicationList();
            for (ExpProvideApplication provideApplication : list) {
                if(null == provideApplication.getAuditQuantity()){
                    return -1;
                }
                provideApplication.setAuditQuantity(provideApplication.getAuditQuantity() * provideApplication.getPackageNum());
                provideApplication.preUpdate();
                int i = dao.updateAuditProvide(provideApplication);
                if(i > 0){
                    num += i;
                }else{
                    return 0;
                }
            }
        }
        return num;
    }

    /**
     * 科室申领物品(申请采购)保存
     * @param expProvideApplication
     * @return
     * @author fengyg
     * @date 2017-06-16
     */
	@Transactional(readOnly = false)
	public int save(ExpProvideApplication expProvideApplication) {
        int num = 0;
        if(null != expProvideApplication && expProvideApplication.getExpProvideApplicationList().size() > 0){
            for (ExpProvideApplication provideApplication : expProvideApplication.getExpProvideApplicationList()) {
                provideApplication.setStorageIn(UserUtils.getUser().getOrgDept().getId());
                if(!provideApplication.getPackageSpec().trim().equals(provideApplication.getMinSpec())){
                    provideApplication.setQuantity(provideApplication.getQuantity() * provideApplication.getPackageNum());
                }
                provideApplication.setQuantityOut(0.00);
                provideApplication.setOutFlag("0");
                provideApplication.preInsert();
                provideApplication.updateOrgId();
                int i = dao.insert(provideApplication);
                if(i > 0){
                    num += i;
                }else{
                    return 0;
                }
            }
        }
		return num;
	}

	@Transactional(readOnly = false)
	public int delete(ExpProvideApplication expProvideApplication) {
		return super.delete(expProvideApplication);
	}

    /**
     * 查询申请出库的数据
     * @param expProvideApplication
     * @return
     * @author fengyg
     */
    public List<ExpProvideApplication> findApplicationExportList(ExpProvideApplication expProvideApplication) {
        return dao.findApplicationExportList(expProvideApplication);
    }

    /**
     * 申请出库数据保存
     * @param expProvideApplication
     * @return
     * @author fengyg
     */
    @Transactional(readOnly = false)
    public int saveProvideApplication(ExpProvideApplication expProvideApplication){
        int num = 0;
        if(null != expProvideApplication){
            ExpExportMaster expExportMaster = new ExpExportMaster();  //出库主表
            expExportMaster.preInsert();
            expExportMaster.setStorageId(expProvideApplication.getExpProvideApplicationList().get(0).getStorageOut());
            expExportMaster.setDocumentNo(expExportService.createDocumentNo(expExportMaster));
            expExportMaster.setExportDate(new Date());
            expExportMaster.setReceiver(expProvideApplication.getExpProvideApplicationList().get(0).getStorageIn());
            List<ExpInoutClass> outList = ExpUtils.getImpOrOutpList("0");  //查询出库类别集合。0，出库；1，入库
            if(null != outList && outList.size() > 0){
                for (ExpInoutClass expInoutClass : outList) {
                    if(expInoutClass.getFromLevel().equals("2")){  //来源等级为 "下级"
                        expExportMaster.setExportClass(expInoutClass.getInOutName());
                    }
                }
            }
            expExportMaster.updateOrgId();
            Double accountReceivable = 0.00;  //应收款

            //出库明细表
            List<ExpProvideApplication> applicationList = expProvideApplication.getExpProvideApplicationList();
            if(null != applicationList && applicationList.size() > 0){
                for(int i = 0; i < applicationList.size(); i++){
                    //减库存操作
                    ExpStock stock = new ExpStock();
                    stock.updateOrgId();
                    stock.setInfoId(applicationList.get(i).getInfoId());
                    stock.setQuantity(applicationList.get(i).getExpStock().getQuantity() * applicationList.get(i).getPackageNum());
                    ExpStock stockQuantity = expStockDao.findByInfoIdQuantity(stock);  //查询要减库存的库存信息
                    //减库存
                    Double quantity = stockQuantity.getQuantity() - (applicationList.get(i).getQuantityOut() * applicationList.get(i).getPackageNum());
                    if(quantity < 0){
                        return -2;
                    }
                    stockQuantity.setQuantity(quantity);
                    int update = expStockDao.update(stockQuantity);
                    if(update > 0){
                        num += update;
                    }else{
                        return 0;
                    }
                    //拼接出库明细
                    ExpExportDetail detail = new ExpExportDetail();
                    detail.preInsert();
                    detail.setMasterId(expExportMaster.getId());
                    detail.setItemNo((i + 1) + "");
                    detail.setInfoId(applicationList.get(i).getInfoId());
                    detail.setExpCode(applicationList.get(i).getExpCode());
                    detail.setPackageNum(applicationList.get(i).getPackageNum() + "");
                    detail.setPackageSpec(applicationList.get(i).getPackageSpec());
                    detail.setPackageUnits(applicationList.get(i).getPackageUnits());
                    detail.setMinSpec(applicationList.get(i).getMinSpec());
                    detail.setMinUnits(applicationList.get(i).getMinUnits());
                    detail.setBatchNo(stockQuantity.getBatchNo());  //批号
                    detail.setExpireDate(stockQuantity.getExpireDate());
                    detail.setPurchasePrice(stockQuantity.getPurchasePrice());
                    detail.setQuantity(applicationList.get(i).getQuantityOut());
                    detail.setInventory(stockQuantity.getQuantity() - (applicationList.get(i).getQuantityOut() * applicationList.get(i).getPackageNum()));
                    detail.setDiscount(stockQuantity.getDiscount());
                    detail.updateOrgId();
                    accountReceivable += applicationList.get(i).getQuantityOut() * stockQuantity.getPurchasePrice();  //计算应收款
                    int insert = expExportDetailDao.insert(detail);  //出库明细保存
                    if(insert > 0){
                        num += insert;
                    }else{
                        return 0;
                    }
                    //修改申请记录的已发数量和发放标志
                    ExpProvideApplication expProvideApplication1 = dao.get(applicationList.get(i).getId());
                    expProvideApplication1.setExpInfoId(expProvideApplication1.getInfoId());
                    Double newQuantityOut = expProvideApplication1.getQuantityOut() + applicationList.get(i).getQuantityOut();
                    expProvideApplication1.setOutFlag("2");  //发放标志
                    expProvideApplication1.preUpdate();
                    int updates = dao.update(expProvideApplication1);
                    if(updates > 0){
                        num += updates;
                    }else{
                        return 0;
                    }
                }
            }
            expExportMaster.setAccountReceivable(accountReceivable);
            int insert = expExportMasterDao.insert(expExportMaster);  //出库主记录保存
            if(insert > 0){
                num += insert;
            }else{
                return 0;
            }
        }
        return num;
    }
    /**
     * 消耗品采购按科室汇总输出pdf
     * @param expProvideApplication
     * @return
     */
    public String findByStorageInPrint(ExpProvideApplication expProvideApplication){
            User user = UserUtils.getUser();
            List<BaseDto> list= dao.findByStorageInPrint(expProvideApplication);
            if(list.size()>0){
                for(BaseDto provide:list){
                    provide.put("packageUnits",DictUtils.getDictLabel(provide.getAsString("packageUnits"),"SPEC_UNIT",""));
                }
            }
            String title="消耗品采购按科室汇总";
            Map map = new HashMap();
            String hospital =  UserUtils.getUser().getCompany().getOrgName();
            map.put("hospital", hospital);
            map.put("startDate", expProvideApplication.getStartDate());
            map.put("stopDate", expProvideApplication.getStopDate());
            map.put("title",title);
            map.put("lists",list);
            String printPath = PrintPdfUtils.previewPdf(user.getId(), "his/csm/findByStorageInPrint.jasper", map, list, "findByStorageInPrint");
            return  printPath;
    }

    /**
     * 消耗品采购按名称汇总输出pdf
     * @param expProvideApplication
     * @return
     */
    public String findByExpNamePrint(ExpProvideApplication expProvideApplication){
            User user = UserUtils.getUser();
            List<BaseDto> list= dao.findByExpNamePrint(expProvideApplication);
            if(list.size()>0){
                for(BaseDto provide:list){
                    provide.put("packageUnits",DictUtils.getDictLabel(provide.getAsString("packageUnits"),"SPEC_UNIT",""));
                }
            }
            String title="消耗品采购按物品汇总";
            Map map = new HashMap();
            String hospital =  UserUtils.getUser().getCompany().getOrgName();
            map.put("hospital", hospital);
            map.put("startDate", expProvideApplication.getStartDate());
            map.put("stopDate", expProvideApplication.getStopDate());
            map.put("title",title);
            map.put("lists",list);
            String printPath = PrintPdfUtils.previewPdf(user.getId(), "his/csm/findByExpNamePrint.jasper", map, list, "findByExpNamePrint");
            return  printPath;
        }
}